package com.qj.yantaishan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qj.yantaishan.common.utils.DateUtils;
import com.qj.yantaishan.common.utils.StringUtils;
import com.qj.yantaishan.domain.*;
import com.qj.yantaishan.mapper.ProductVoMapper;
import com.qj.yantaishan.service.*;
import com.qj.yantaishan.vo.ProductVo;
import com.qj.yantaishan.vo.ShanglalaProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Primary
@Slf4j
public class IProductVoServiceImpl extends ServiceImpl<ProductVoMapper, ProductVo> implements IProductVoService {
    @Autowired
    private IProductSkuService productSkuService;
    @Autowired
    private IProductPropertyService productPropertyService;
    @Autowired
    private IProductPropertyValueService productPropertyValueService;
    @Autowired
    private IProductCategoryService productCategoryService;
    @Autowired
    private IProductCustomFieldService productCustomFieldService;
    @Autowired
    private IProductToGroupService productToGroupService;
    @Autowired
    private IProductGroupService productGroupService;

    @Override
    public Page<ProductVo> getProductPage(Page<ProductVo> page, String sort, String orderBy, String keyword) {
        QueryWrapper<ProductVo> queryWrapper = new QueryWrapper<>();
        if (sort.equals("desc")) queryWrapper.orderByDesc(orderBy);
        else queryWrapper.orderByAsc(orderBy);
        queryWrapper.like("name", keyword);
        Page<ProductVo> page1 = page(page, queryWrapper);
        Collection<ProductVo> productVoList = page1.getRecords();

        //{product:{skuList:[{properties:[{typeName:xxx,propertiesValue:{xxx}}]}]}}
        page.setRecords(supperProductVoList(productVoList));
        return null;
    }

    @Override
    public ProductVo getProductDetails(Integer productId) {
        //{product:{skuList:[{properties:[{typeName:xxx,propertiesValue:{xxx}}]}]}}
        //获取商品信息
        ProductVo product = getById(productId);
        //商品分类
        Long categoryId = product.getStoreCategoryId();
        if (categoryId != 0) {
            List<Integer> ids = new ArrayList<>();
            ProductCategory category = productCategoryService.getOne(new LambdaQueryWrapper<ProductCategory>().eq(ProductCategory::getCatId, categoryId));
            while (category != null ) {
                ids.add(category.getCatId());
                category = productCategoryService.getOne(new LambdaQueryWrapper<ProductCategory>().eq(ProductCategory::getCatId, category.getCatFid()));
            }
            Collections.reverse(ids);
            product.setCategoryIds(ids);
        }

        List<ProductToGroup> productToGroups = productToGroupService.list(new LambdaQueryWrapper<ProductToGroup>().eq(ProductToGroup::getProductId, product.getProductId()));
        if (productToGroups != null && productToGroups.size() > 0) {
            String groupName = "";
            for (ProductToGroup productToGroup : productToGroups) {
                ProductGroup group = productGroupService.getById(productToGroup.getGroupId());
                if (StringUtils.isNotEmpty(groupName)) {
                    groupName += "," + group.getGroupName();
                } else {
                    groupName += group.getGroupName();
                }
                product.setGroupName(groupName);
            }
        } else {
            product.setGroupName("暂无分组");
        }
        if (product.getStatus().equals("2")) {
            return null;
        }
        //查询商品自定义字段
        List<ProductCustomField> productCustomFieldList = productCustomFieldService.list(new QueryWrapper<ProductCustomField>().eq("product_id", productId));
        product.setProductCustomFieldList(productCustomFieldList);
        //获取商品对应的sku
        List<ProductSku> skuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, product.getProductId()));
        //遍历sku得出它的属性与属性值  properties
        Collection<ProductSku> productSkus = skuList.stream().map(sku -> {
            //sku属性与属性值 properties: 属性(property):(property_value)属性值;属性:属性值...
            String properties = sku.getProperties();

            String[] propertiesArr = properties.split(";");

            List<ProductProperty> productPropertyList = new ArrayList<>();
            if (propertiesArr != null && propertiesArr.length >= 2) {
                //多个 属性对
                for (String properties1 : propertiesArr) {
                    //properties1 属性(property):(property_value)属性值
                    //切割查询属性or属性值
                    String[] propertyAndValue = properties1.split(":");
                    //查询属性
                    ProductProperty property = productPropertyService.getOne(new QueryWrapper<ProductProperty>().eq("pid", propertyAndValue[0]));
                    //查询属性值
                    ProductPropertyValue propertyValue = productPropertyValueService.getOne(new QueryWrapper<ProductPropertyValue>().eq("vid", propertyAndValue[1]));
                    if (product != null) {
                        property.setProductPropertyValue(propertyValue);
                    }
                    productPropertyList.add(property);
                }
            } else if (propertiesArr != null && propertiesArr.length >= 1) {
                String[] propertyAndValue = propertiesArr[0].split(":");
                ProductProperty property = productPropertyService.getOne(new QueryWrapper<ProductProperty>().eq("pid", propertyAndValue[0]));
                ProductPropertyValue propertyValue = productPropertyValueService.getOne(new QueryWrapper<ProductPropertyValue>().eq("vid", propertyAndValue[1]));
                if (product != null) {
                    property.setProductPropertyValue(propertyValue);
                }
                productPropertyList.add(property);
            }

            sku.setProductPropertyList(productPropertyList);
            return sku;
        }).collect(Collectors.toList());
        product.setProductSkuList(skuList);
        return product;
    }

    @Override
    @Transactional
    public int mySave(ProductVo productVo1) {

        List<ProductCustomField> productCustomFieldList1 = productVo1.getProductCustomFieldList();
        if (productCustomFieldList1 != null && productCustomFieldList1.size() >= 1) productVo1.setHasCustom(1);
        else productVo1.setHasCustom(0);


        //1.1查出category
        ProductCategory category = productCategoryService.getOne(new LambdaQueryWrapper<ProductCategory>().eq(ProductCategory::getCatId, productVo1.getStoreCategoryId()));
        if (category != null) {
            productVo1.setCategoryFid(category.getCatFid());
            productVo1.setHasCategory(1);
        }
        // TODO: 2022/8/2 保存productToGroup
        String groupIds = productVo1.getGroupIds();
        if (StringUtils.isNotEmpty(groupIds)) {
            //不为空则有分组添加productToGroup
            //尝试切割
            String[] groupIdList = groupIds.split(",");
            if (groupIdList != null && groupIdList.length >= 1) {
                //有多个分组
                for (String groupIdd : groupIdList) {
                    ProductToGroup productToGroup = new ProductToGroup();
                    productToGroup.setProductId(productVo1.getProductId().longValue());
                    productToGroup.setGroupId(Long.parseLong(groupIdd));
                    productToGroupService.save(productToGroup);
                }
            } else {
                // 只有一个分组
                ProductToGroup productToGroup = new ProductToGroup();
                productToGroup.setProductId(productVo1.getProductId().longValue());
                productToGroup.setGroupId(Long.parseLong(groupIds));
                productToGroupService.save(productToGroup);
            }
        }
        //1.2保存product
        save(productVo1);
        saveSku(productVo1);
        //5.保存customFieldList
        List<ProductCustomField> productCustomFieldList = productVo1.getProductCustomFieldList();
        if (productCustomFieldList != null && productCustomFieldList.size() >= 1) {
            for (ProductCustomField productCustomField : productCustomFieldList) {
                productCustomField.setProductId(productVo1.getProductId());
                productCustomFieldService.save(productCustomField);
            }
        }
        return 0;
    }

    private void saveSku(ProductVo productVo1) {
        List<ProductSku> productSkuList = productVo1.getProductSkuList();
        if (productSkuList != null && productSkuList.size() >= 1) {
            productVo1.setHasProperty(1);
        } else {
            productVo1.setHasProperty(0);
        }
        //2.保存skuList

        if (productSkuList != null && productSkuList.size() >= 2) {
            //多个sku
            for (ProductSku productSku : productSkuList) {
                //propertyList?
                getSku(productVo1, productSku);
            }
        } else if (productSkuList != null && productSkuList.size() >= 1) {
            //单个sku
            getSku(productVo1, productSkuList.get(0));

        }
    }

    @Override
    public int myUpdate(ProductVo productVo) {
        /**
         * 修改商品信息思路
         * 一、customFieldList   可能会多   可能会少   可能不多不少但却发生了改变
         *      1.1 不管三七二十一现将之前的全部删除  √
         *         1.1.1 before delete by productId   after  for insert
         *      1.2 直接一波updateById 紧接着看哪个没id就new 然后 insert
         *         1.2.1 before updateById
         * 二、skuList    可能会多   可能会少   可能不多不少但却发生了改变
         *      1.1 不管三七二十一现将之前的全部删除  √
         *          1.1.1 before delete by productId   after  for insert
         */

        Long storeCategoryId = productVo.getStoreCategoryId();
        if (storeCategoryId != null && storeCategoryId != 0) {

            //有分类id 我找他爹 搞层级
        }
        //1.更新商品本身
        String groupIds = productVo.getGroupIds();
        productToGroupService.remove(new LambdaQueryWrapper<ProductToGroup>().eq(ProductToGroup::getProductId, productVo.getProductId()));
        if (StringUtils.isNotEmpty(groupIds)) {
            //不为空则有分组添加productToGroup
            //尝试切割
            String[] groupIdList = groupIds.split(",");
            if (groupIdList != null && groupIdList.length >= 1) {
                //有多个分组
                for (String groupIdd : groupIdList) {
                    ProductToGroup productToGroup = new ProductToGroup();
                    productToGroup.setProductId(productVo.getProductId().longValue());
                    productToGroup.setGroupId(Long.parseLong(groupIdd));
                    productToGroupService.save(productToGroup);
                }
            } else {
                // 只有一个分组
                ProductToGroup productToGroup = new ProductToGroup();
                productToGroup.setProductId(productVo.getProductId().longValue());
                productToGroup.setGroupId(Long.parseLong(groupIds));
                productToGroupService.save(productToGroup);
            }
        }
        updateById(productVo);
        //2.更新customFieldList
        //2.1删除customFieldList
        productCustomFieldService.remove(new LambdaQueryWrapper<ProductCustomField>().eq(ProductCustomField::getProductId, productVo.getProductId()));
        //2.2插入
        List<ProductCustomField> productCustomFieldList = productVo.getProductCustomFieldList();
        if (productCustomFieldList != null && productCustomFieldList.size() >= 1) {
            for (ProductCustomField productCustomField : productCustomFieldList) {
                productCustomField.setProductId(productVo.getProductId());
                productCustomFieldService.save(productCustomField);
            }
        }
        //3.更新sku
        //3.1删除sku
        productSkuService.remove(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, productVo.getProductId()));
        //3.2插入sku
        saveSku(productVo);

        return 0;
    }

    @Override
    public int delete(Integer productId) {
        //假删除product
        update(new LambdaUpdateWrapper<ProductVo>().set(ProductVo::getStatus, 2).eq(ProductVo::getProductId, productId));

        return 0;
    }

    @Override
    public int getProductCountByCategoryId(Integer catId) {
        ProductVoMapper productVoMapper = getBaseMapper();
        return productVoMapper.getProductCountByCategoryId(catId);

    }

    @Override
    public int getProductCountByFatherCategoryId(Integer catId) {
        ProductVoMapper productVoMapper = getBaseMapper();
        return productVoMapper.getProductCountByFatherCategoryId(catId);
    }

    @Override
    public List<ShanglalaProductVo> handleSkuList(List<ShanglalaProductVo> records) {
        if (records != null){
            for (ShanglalaProductVo product : records){
                //获取商品对应的sku
                List<ProductSku> skuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, product.getProductId()));
                //遍历sku得出它的属性与属性值  properties
                Collection<ProductSku> productSkus = skuList.stream().map(sku -> {
                    //sku属性与属性值 properties: 属性(property):(property_value)属性值;属性:属性值...
                    String properties = sku.getProperties();

                    String[] propertiesArr = properties.split(";");

                    List<ProductProperty> productPropertyList = new ArrayList<>();
                    if (propertiesArr != null && propertiesArr.length >= 2) {
                        //多个 属性对
                        for (String properties1 : propertiesArr) {
                            //properties1 属性(property):(property_value)属性值
                            //切割查询属性or属性值
                            String[] propertyAndValue = properties1.split(":");
                            //查询属性
                            ProductProperty property = productPropertyService.getOne(new QueryWrapper<ProductProperty>().eq("pid", propertyAndValue[0]));
                            //查询属性值
                            ProductPropertyValue propertyValue = productPropertyValueService.getOne(new QueryWrapper<ProductPropertyValue>().eq("vid", propertyAndValue[1]));
                            if (product != null) {
                                property.setProductPropertyValue(propertyValue);
                            }
                            productPropertyList.add(property);
                        }
                    } else if (propertiesArr != null && propertiesArr.length >= 1) {
                        String[] propertyAndValue = propertiesArr[0].split(":");
                        ProductProperty property = productPropertyService.getOne(new QueryWrapper<ProductProperty>().eq("pid", propertyAndValue[0]));
                        ProductPropertyValue propertyValue = productPropertyValueService.getOne(new QueryWrapper<ProductPropertyValue>().eq("vid", propertyAndValue[1]));
                        if (product != null) {
                            property.setProductPropertyValue(propertyValue);
                        }
                        productPropertyList.add(property);
                    }

                    sku.setProductPropertyList(productPropertyList);
                    return sku;
                }).collect(Collectors.toList());
                product.setProductSkuList(skuList);
            }
        }

        return records;
    }

    private void getSku(ProductVo productVo1, ProductSku productSku) {
        List<ProductProperty> productPropertyList = productSku.getProductPropertyList();
        String properties = "";
        /**
         * "productPropertyList": [
         *                 {
         *                     "name": "容量",
         *                     "productPropertyValue": {
         *                         "value": "500ML",
         *                         "image": "http://img30.360buyimg.com/popWaterMark/jfs/t1/37786/34/12537/153890/5d105f2eE96032943/cdd980fce545e1b7.jpg"
         *                     }
         *                 },
         *                 {
         *                     "name": "度数",
         *                     "productPropertyValue": {
         *                         "value":"56°",
         *                         "image": "http://img30.360buyimg.com/popWaterMark/jfs/t1/37786/34/12537/153890/5d105f2eE96032943/cdd980fce545e1b7.jpg"
         *                     }
         *                 }
         *             ]
         */
        if (productPropertyList != null && productPropertyList.size() >= 2) {
            for (ProductProperty productProperty : productPropertyList) {
                String pidAndVid = "";
                //多个属性值对  property-->propertyValue-->pid:vid
                //先查询property是否存在
                Integer pid = 0;
                List<ProductProperty> productProperties = productPropertyService.list(new LambdaQueryWrapper<ProductProperty>().eq(ProductProperty::getName, productProperty.getName()));
                if (productProperties != null && productProperties.size() >= 1) {
                    //property已经存在获取pid
                    ProductProperty productProperty1 = productProperties.get(0);
                    pid = productProperty1.getPid();

                } else {
                    //property不存在 创建
                    ProductProperty productProperty1 = new ProductProperty();
                    productProperty1.setProductId(productVo1.getProductId().longValue());
                    productProperty1.setName(productProperty.getName());
                    productPropertyService.save(productProperty1);
                    pid = productProperty1.getPid();
                }
                //创建propertyValue
                ProductPropertyValue productPropertyValue = productProperty.getProductPropertyValue();
                productPropertyValue.setPid(pid);

                productPropertyValue.setIsOn(1);
                productPropertyValueService.save(productPropertyValue);
                Integer vid = productPropertyValue.getVid();
                if (properties.equals("")) {
                    //第一条
                    properties += "" + pid + ":" + vid;
                } else {
                    //后面的
                    properties += ";" + pid + ":" + vid;
                }
            }


        } else {
            //  单个属性值对 property-->propertyValue-->pid:vid
            ProductProperty productProperty = productPropertyList.get(0);
            String pidAndVid = "";
            //多个属性值对  property-->propertyValue-->pid:vid
            //先查询property是否存在
            Integer pid = 0;
            List<ProductProperty> productProperties = productPropertyService.list(new LambdaQueryWrapper<ProductProperty>().eq(ProductProperty::getName, productProperty.getName()));
            if (productProperties != null && productProperties.size() >= 1) {
                //property已经存在获取pid
                ProductProperty productProperty1 = productProperties.get(0);
                pid = productProperty1.getPid();

            } else {
                //property不存在 创建
                ProductProperty productProperty1 = new ProductProperty();
                productProperty1.setName(productProperty.getName());
                productPropertyService.save(productProperty1);
                pid = productProperty1.getPid();
            }
            //创建propertyValue
            ProductPropertyValue productPropertyValue = productProperty.getProductPropertyValue();
            productPropertyValue.setPid(pid);

            productPropertyValue.setIsOn(1);
            productPropertyValueService.save(productPropertyValue);
            Integer vid = productPropertyValue.getVid();
            if (properties.equals("")) {
                //第一条
                properties += "" + pid + ":" + vid;
            } else {
                //后面的
                properties += ";" + pid + ":" + vid;
            }
        }
        productSku.setProperties(properties);
        productSku.setProductId(productVo1.getProductId());
        productSku.setIsOn(1);
        productSku.setSaleMinPrice(productSku.getPrice());
        productSku.setSaleMaxPrice(productSku.getPrice());
        productSku.setProductId(productVo1.getProductId());
        productSkuService.save(productSku);
    }

    private List<ProductVo> supperProductVoList(Collection<ProductVo> productVoList) {
        List<ProductVo> productVoList1 = productVoList.stream().map(product -> {
            product.setProductCategory(productCategoryService.getOne(new LambdaQueryWrapper<ProductCategory>().eq(ProductCategory::getCatId, product.getCategoryId())));
            //product-->skuList-->propertiesList-->propertiesValue
            List<ProductSku> skuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, product.getProductId()));
            List<ProductSku> collect = skuList.stream().map(sku -> {

                return sku;
            }).collect(Collectors.toList());
            return product;
        }).collect(Collectors.toList());
        return null;
    }
}
